/*
 *  Settings.cpp
 *  GRE
 *
 *  Created by Kutlak Roman on 07/09/2011.
 *  Copyright 2011 University of Aberdeen. All rights reserved.
 *
 */

#include <iostream>
#include <fstream>
#include <sys/stat.h>

#include "Settings.h"

namespace kutlak {
namespace roman {
namespace gre {
    
    using std::ifstream;
    using std::string;
    using std::cerr;
    using std::endl;
    
    std::once_flag Settings::sFlag;
    
#pragma mark -
#pragma mark lifecycle
    
    Settings& Settings::Instance()
    {
        static std::unique_ptr<Settings> sInstance;
        string path = "/Users/roman/.gre/gre.settings";
        std::call_once(sFlag, [&path]() {
            sInstance = std::unique_ptr<Settings>(new Settings(path));
        });
        
        return *sInstance;
    }
    
    Settings::Settings(const std::string& path) : mSpecSettings()
    {
        Init(path);
    } // Settings
    
    Settings::~Settings() = default;
    
#pragma mark -
#pragma mark operations
    //=============================  OPERATIONS  ===============================
    
    string Settings::GetSetting(const string& key)
    {
        string result = "";
        auto val = mSpecSettings.find(key);
        if (mSpecSettings.end() != val)
            result = val->second;
        
        return result;
    }
    
    
    // static method
    string Settings::GetEnvironmentVar(const string& key)
    {                                 
        char* val = getenv(key.c_str());
        std::string retval = "";
        if (val != NULL) {
            retval = val;
        }
        return retval;
    }
    
#pragma mark -
#pragma mark protected
    ///////////////////////////////  PROTECTED   ///////////////////////////////
    void Settings::Init(const std::string& path) {
        ifstream input(path.c_str());
        
        if (!input.is_open())
        {
            cerr << __FILE__ << " (" << __LINE__ << "): ";
            cerr << "Could not open the input file ";
            cerr << path << endl;
        }
        
        string key, value;
        while (input >> key >> value)
        {
            if (key[0] != '#')  // ignore lines starting with #
                mSpecSettings.emplace(std::move(key),
                                      std::move(value));
        }
        
        input.close();
    }
}
}
}
